package com.x.redcube.util;

import com.x.framework.exception.BusinessException;
import org.apache.tomcat.util.codec.binary.Base64;

import java.security.MessageDigest;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

public class DigestUtils {
    private static final String MD_ALGORITHM = "SHA-1";
    private static final String KEY_ALGORITHM = "AES";
    private static final String INS_ALGORITHM = "AES";

    /**
     * AES加密 SHA-1摘要
     *
     * @param content  需要做摘要的内容
     * @param password 加密密钥
     * @return
     */
    public static String digest(String password, String content) {
        try {
            byte[] key = password.getBytes();
            SecretKeySpec secretKeySpec = new SecretKeySpec(key, KEY_ALGORITHM);
            Cipher cipher = Cipher.getInstance(INS_ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
            byte[] encrypted = cipher.doFinal(content.getBytes(Constant.UTF_8));
            MessageDigest sha = MessageDigest.getInstance(MD_ALGORITHM);
            encrypted = sha.digest(encrypted);
            return Base64.encodeBase64String(encrypted);
        } catch (Exception e) {
            throw new BusinessException(e);
        }
    }

    /**
     * 验证摘要
     *
     * @param digestStr 摘要
     * @param content   需要做摘要的内容
     * @param password  加密密钥
     * @return
     */
    public static boolean verify(String digestStr, String password, String content) {
        try {
            String digest = digest(password, content);
            return digestStr.equals(digest);
        } catch (Exception e) {
            throw new BusinessException(e);
        }
    }

    public static void main(String[] args) {
        String password = "1234567812345678";
        String content = "abcdefgabcdefgabcdefgabcdefgabcdefgabcdefg";
        String encode = digest(password, content);
        System.out.println(encode);
        System.out.println(verify(encode, password, content));

    }
}